package com.example.lovebond.controller;

import com.example.lovebond.common.HttpResult;
import com.example.lovebond.dao.mapper.generatedMapper.BondMapper;
import com.example.lovebond.dao.mapper.generatedMapper.LoveBondUserMapper;
import com.example.lovebond.dao.model.BondExample;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@RestController
@RequestMapping("/user")
public class UserController {

    private final BondMapper bondMapper;
    private final LoveBondUserMapper loveBondUserMapper;

    public UserController(LoveBondUserMapper loveBondUserMapper, BondMapper bondMapper) {
        this.loveBondUserMapper = loveBondUserMapper;
        this.bondMapper = bondMapper;
    }

    @GetMapping("/info")
    public HttpResult selectUserInfo(@RequestParam("userId") String userId) {
        var user = this.loveBondUserMapper.selectByPrimaryKey(userId);

        var bondExampleOwner = new BondExample();
        bondExampleOwner.createCriteria().andOwnerIdEqualTo(userId).andIssuerIdEqualTo(user.getMateId());
        var ownerBonds = this.bondMapper.selectByExample(bondExampleOwner);

        var bondExampleIssuer = new BondExample();
        bondExampleIssuer.createCriteria().andOwnerIdEqualTo(user.getMateId()).andIssuerIdEqualTo(userId);
        var issuerBonds = this.bondMapper.selectByExample(bondExampleIssuer);

        var userInfo = new HashMap<String, Object>();
        userInfo.put("user", user);
        userInfo.put("ownerBonds", ownerBonds);
        userInfo.put("issuerBonds", issuerBonds);
        return HttpResult.ok(userInfo);
    }

    @GetMapping("/get-all-cookies")
    public String getAllCookies(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            StringBuilder cookieInfo = new StringBuilder("All Cookies:\n");
            for (Cookie cookie : cookies) {
                cookieInfo.append("Name: ").append(cookie.getName())
                        .append(", Value: ").append(cookie.getValue())
                        .append("\n");
            }
            return cookieInfo.toString();
        } else {
            return "No cookies found.";
        }
    }
}
